# trans 2022-01-01 15:20:33 to 412857.67
# trans 412857.67 to 2022-01-01 15:20:33

library(stringr)

my_floor <- function(num = 0, digits = 0){
    return(floor(num*(10^digits))/(10^digits))
}


float_time <- function(number = 44400.33876, origin = "1899-12-30", sepper = " "){

  int_num <- my_floor(number, 0)
  float_num <- number - int_num
  int_date <- as.Date(int_num, origin = as.Date("1899-12-30"))
  
  totalsecond <- my_floor(float_num*86400,0)
  hour <- my_floor(totalsecond/3600, 0)
  minute <- my_floor((totalsecond - hour*3600)/60, 0)
  second <- totalsecond - hour*3600 - minute * 60
  
  outstr <- paste(as.character(int_date), sepper, hour, ":", minute, ":", second, sep = "")
  return(outstr)
}


time_float <- function(str = "2021-07-23 8:7:48", middlesep = " ", timesep = ":", origin = "1899-12-30"){
  date_str <- str_split(str = str, middlesep)[[1]][1]
  time_str <- str_split(str = str, middlesep)[[1]][2]
  time_vec <- c(0, 0, 0)
  time_raw_vec <- str_split(str = time_str, timesep)[[1]]
  if(length(time_raw_vec) >= 3){
    time_vec[1] <- time_raw_vec[1]
    time_vec[2] <- time_raw_vec[2]
    time_vec[3] <- time_raw_vec[3]
  }else{
    for(i in 1:length(time_raw_vec)){
      time_vec[i] <- time_raw_vec[i]
    }
    for(i in (length(time_raw_vec)+1):3){
      time_vec[i] <- 0
    }
  }
  return(round(as.numeric(as.Date(date_str) - as.Date(origin)) + 
           (as.numeric(time_vec[1])*3600 + as.numeric(time_vec[2])*60 + as.numeric(time_vec[3]))/86400, 5))
}

#### TEST AREA ####
# my_floor(3.5678, 3)
# my_floor(375800, -4)
# float_time(number = 45136.87772)
# time_float(str = "2023-07-29 21:3:55")
